package com.xiaoxing.utils;


import com.xiaoxing.domain.ResponseResult;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.Map;
/**
 * @description:请求http 得到返回结果的方法类
 * @author: lyg
 * @create: 2023-10-16 16:15
 **/

@Slf4j
public class HttpConnectionUtil {

	public static ResponseResult doGet(String httpUrl, Map params) throws UnsupportedEncodingException {
		//url处理
		httpUrl = initParamsOrUrl(httpUrl, params,"GET");
		//设置返回数据
		StringBuilder response = new StringBuilder();
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方法
			conn.setRequestMethod("GET");
			int responseCode = conn.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 读取响应内容
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String inputLine;
				while ((inputLine = in.readLine()) != null) {
					response.append(inputLine);
				}
				in.close();
				// 输出响应内容
				System.out.println(response);
			} else {
				System.out.println("Request failed");
			}
		} catch (MalformedURLException e) {
			log.info("生成url失败");
		} catch (ProtocolException e) {
			log.info("请求方法设置失败");
		} catch (IOException e) {
			log.info("获取HttpURLConnection失败");
		}
		return ResponseResult.okResult(response);
	}

	public static ResponseResult doPost(String httpUrl, Map params) {
		StringBuilder response = new StringBuilder();
		try {
			// 创建URL对象
			URL url = new URL(httpUrl);
			// 打开连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方法
			conn.setRequestMethod("POST");
			// 启用输出流
			conn.setDoOutput(true);
			// 将参数写入请求的Body中
			String parameters = initParamsOrUrl(httpUrl, params,"POST");
			OutputStream out = conn.getOutputStream();
			out.write(parameters.getBytes());
			out.flush();
			out.close();

			// 发送请求
			int responseCode = conn.getResponseCode();

			// 根据响应码判断请求是否成功
			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 读取响应内容
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String inputLine;
				while ((inputLine = in.readLine()) != null) {
					response.append(inputLine);
				}
				in.close();

				// 输出响应内容
				System.out.println(response.toString());
			}
		} catch (MalformedURLException e) {
			log.info("生成url失败");
		} catch (ProtocolException e) {
			log.info("请求方法设置失败");
		} catch (IOException e) {
			log.info("获取HttpURLConnection失败");
		}
		return ResponseResult.okResult(response);
	}

	private static String initParamsOrUrl(String httpUrl, Map params,String flag) throws UnsupportedEncodingException {
		//获取map的迭代器
		Iterator iterator = params.entrySet().iterator();
		if(flag.equals("GET")) {
			httpUrl = httpUrl + "?";
			while (iterator.hasNext()) {
				Map.Entry<String, String> next = (Map.Entry<String, String>) iterator.next();
				httpUrl = httpUrl + next.getKey() + "=" + URLEncoder.encode(next.getValue(), "UTF-8") + "&";
			}
			return httpUrl.substring(0, httpUrl.length() - 1);
		}else if (flag.equals("POST")){
			String postParam="";
			while (iterator.hasNext()) {
				Map.Entry<String, String> next = (Map.Entry<String, String>) iterator.next();
				postParam = postParam+next.getKey() + "=" + URLEncoder.encode(next.getValue(), "UTF-8") + "&";
			}
			return postParam;
		}else {
			return null;
		}
	}
}
